 package com.example.sms_listener

import android.os.Handler
import android.os.Looper
import android.util.Log
import io.flutter.plugin.common.EventChannel

/**
 * SMS事件流处理器
 * 
 * 负责处理EventChannel的数据传递，将Android端接收到的短信数据发送到Flutter端
 */
class SmsEventStreamHandler : EventChannel.StreamHandler {
    
    companion object {
        private const val TAG = "SmsEventStreamHandler"
    }
    
    /// 事件流发送器
    private var eventSink: EventChannel.EventSink? = null
    
    /// 主线程Handler
    private val mainHandler = Handler(Looper.getMainLooper())

    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        Log.d(TAG, "Flutter端开始监听事件流")
        eventSink = events
    }

    override fun onCancel(arguments: Any?) {
        Log.d(TAG, "Flutter端取消监听事件流")
        eventSink = null
    }

    /**
     * 发送短信事件到Flutter端
     * 
     * @param smsData 短信数据Map
     */
    fun sendSmsEvent(smsData: HashMap<String, Any>) {
        Log.d(TAG, "准备发送短信数据到Flutter端: $smsData")
        
        // 确保在主线程中发送数据
        mainHandler.post {
            try {
                eventSink?.let { sink ->
                    sink.success(smsData)
                    Log.d(TAG, "短信数据已发送到Flutter端")
                } ?: run {
                    Log.w(TAG, "EventSink为空，无法发送数据到Flutter端")
                }
            } catch (e: Exception) {
                Log.e(TAG, "发送数据到Flutter端时发生错误", e)
                eventSink?.error("SEND_ERROR", "发送数据失败: ${e.message}", null)
            }
        }
    }

    /**
     * 发送错误信息到Flutter端
     * 
     * @param errorCode 错误代码
     * @param errorMessage 错误消息
     * @param errorDetails 错误详情
     */
    fun sendError(errorCode: String, errorMessage: String, errorDetails: Any? = null) {
        Log.e(TAG, "发送错误到Flutter端: $errorCode - $errorMessage")
        
        mainHandler.post {
            try {
                eventSink?.error(errorCode, errorMessage, errorDetails)
            } catch (e: Exception) {
                Log.e(TAG, "发送错误信息时发生异常", e)
            }
        }
    }

    /**
     * 检查是否有活跃的监听器
     */
    fun hasActiveListener(): Boolean {
        return eventSink != null
    }

    /**
     * 清理资源
     */
    fun cleanup() {
        eventSink = null
    }
}